<template>
  <div class="container bgc-default pad-20">
    <div class="bg-color-white pad-20">
      <!-- 表单区域 -->
      <el-form ref="template" :model="template" label-width="100px" :rules="rules">
        <el-form-item label="模版名称:" inline="true" prop="templateName">
          <el-input v-model="template.templateName" style="width:400px" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="模版类型:" prop="templateType">
          <el-radio-group v-model="template.templateType">
            <el-radio label="1">快递</el-radio>
            <el-radio label="2">物流</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="计费方式:" prop="feeType">
          <el-radio-group v-model="template.feeType">
            <el-radio label="1">按商品件数</el-radio>
            <el-radio label="2">按商品重量</el-radio>
            <el-radio label="3">按商品体积</el-radio>
          </el-radio-group>
          <el-form>
            <el-form-item><el-checkbox true-label="1" v-model="template.countryFlag">使用默认运费</el-checkbox>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <span style="color:#C2C2C2">(勾选后添加配送区域为全国的默认运费)</span>
          </el-form-item>  
          </el-form>
          <el-form v-if="template.countryFlag==1" label-width="100px" class="bill-box">
            <el-form-item v-if="template.feeType == 1"><el-input v-model="template.startItemStandard" @keyup.native="template.startItemStandard = checkInputPositiveNum(template.startItemStandard)" /></el-form-item><span v-if="template.feeType == 1" class="mar-l-5">件以内(含),运费</span>
            <el-form-item v-if="template.feeType == 1"><el-input v-model="template.startItemFee" @keyup.native="template.startItemFee = checkInputNum(template.startItemFee)" /></el-form-item><span v-if="template.feeType == 1" class="mar-l-5">元,每增加</span>
            <el-form-item v-if="template.feeType == 1"><el-input v-model="template.addItemStandard" @keyup.native="template.addItemStandard = checkInputPositiveNum(template.addItemStandard)" /></el-form-item><span v-if="template.feeType == 1" class="mar-l-5">件,运费增加</span>
            <el-form-item v-if="template.feeType == 1"><el-input v-model="template.addItemFee" @keyup.native="template.addItemFee = checkInputNum(template.addItemFee)" /></el-form-item><span v-if="template.feeType == 1" class="mar-l-5">元</span>
            <el-form-item v-if="template.feeType == 2"><el-input v-model="template.startWeightStandard" @keyup.native="template.startWeightStandard = checkInputPositiveNum(template.startWeightStandard)" /></el-form-item><span v-if="template.feeType == 2" class="mar-l-5">kg以内(含),运费</span>
            <el-form-item v-if="template.feeType == 2"><el-input v-model="template.startWeightFee" @keyup.native="template.startWeightFee = checkInputNum(template.startWeightFee)" /></el-form-item><span v-if="template.feeType == 2" class="mar-l-5">元,每增加</span>
            <el-form-item v-if="template.feeType == 2"><el-input v-model="template.addWeightStandard" @keyup.native="template.addWeightStandard = checkInputPositiveNum(template.addWeightStandard)" /></el-form-item><span v-if="template.feeType == 2" class="mar-l-5">kg,运费增加</span>
            <el-form-item v-if="template.feeType == 2"><el-input v-model="template.addWeightFee" @keyup.native="template.addWeightFee = checkInputNum(template.addWeightFee)" /></el-form-item><span v-if="template.feeType == 2" class="mar-l-5">元</span>
            <el-form-item v-if="template.feeType == 3"><el-input v-model="template.startVolumeStandard" @keyup.native="template.startVolumeStandard = checkInputPositiveNum(template.startVolumeStandard)" /></el-form-item><span v-if="template.feeType == 3" class="mar-l-5">立方米以内(含),运费</span>
            <el-form-item v-if="template.feeType == 3"><el-input v-model="template.startVolumeFee" @keyup.native="template.startVolumeFee = checkInputNum(template.startVolumeFee)" /></el-form-item><span v-if="template.feeType == 3" class="mar-l-5">元,每增加</span>
            <el-form-item v-if="template.feeType == 3"><el-input v-model="template.addVolumeStandard" @keyup.native="template.addVolumeStandard = checkInputPositiveNum(template.addVolumeStandard)" /></el-form-item><span v-if="template.feeType == 3" class="mar-l-5">立方米,运费增加</span>
            <el-form-item v-if="template.feeType == 3"><el-input v-model="template.addVolumeFee" @keyup.native="template.addVolumeFee = checkInputNum(template.addVolumeFee)" /></el-form-item><span v-if="template.feeType == 3" class="mar-l-5">元</span>
          </el-form>
        </el-form-item>
      </el-form>
      <!-- 运费取用 -->
      <div class="mar-l-25 pad-5" style="background:#ECF5FF;width:65%;border:1px solid #C6E2FF">
        <h5>运费取用</h5>
        <p>1. 当“不配送区域”有设置时优先验证，若收货地址在不配送范围内，商品不配送。</p>
        <p>2. 若“配送区域”中存在收货地址所在的区域，根据区域规则计算商品运费。</p>
        <p>3. 若“配送区域”中不存在收货地址所在的区域，且勾选并设置了“使用默认运费”，根据默认运费规则计算商品运费。</p>
        <p>4. 以上1~3条件均不符合的商品不配送。</p>
      </div>
      <!-- 配送区域设置 -->
      <el-form label-width="100px" class="mar-t-20">
        <el-form-item label="配送区域:">
          <el-button type="text" @click="showAddDetail">添加配送区域运费</el-button>
        </el-form-item>
        <el-form-item>
          <el-table :data="template.templateDetailsList">
            <el-table-column :key="Math.random()" label="配送区域" prop="areaNames">
              <template slot-scope="scope">
                {{formatAreaList(scope.row.templateAreaList||[])}}
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" v-if="template.feeType == 1" label="首件(件)" prop="startItemStandard">
              <template slot-scope="scope">
                <el-input v-model="scope.row.startItemStandard" @keyup.native="scope.row.startItemStandard = checkInputPositiveNum(scope.row.startItemStandard)">编辑区域</el-input>
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" v-if="template.feeType == 1" label="运费(元)" prop="startItemFee">
              <template slot-scope="scope">
                <el-input v-model="scope.row.startItemFee" @keyup.native="scope.row.startItemFee = checkInputNum(scope.row.startItemFee)">编辑区域</el-input>
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" v-if="template.feeType == 1" label="续件(件)" prop="addItemStandard">
              <template slot-scope="scope">
                <el-input v-model="scope.row.addItemStandard" @keyup.native="scope.row.addItemStandard = checkInputPositiveNum(scope.row.addItemStandard)">编辑区域</el-input>
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" v-if="template.feeType == 1" label="续费(元)" prop="addItemFee">
              <template slot-scope="scope">
                <el-input v-model="scope.row.addItemFee" @keyup.native="scope.row.addItemFee = checkInputNum(scope.row.addItemFee)">编辑区域</el-input>
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" v-if="template.feeType == 2" label="首件(kg)" prop="startWeightStandard">
              <template slot-scope="scope">
                <el-input v-model="scope.row.startWeightStandard" @keyup.native="scope.row.startWeightStandard = checkInputPositiveNum(scope.row.startWeightStandard)">编辑区域</el-input>
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" v-if="template.feeType == 2" label="运费(元)" prop="startWeightFee">
              <template slot-scope="scope">
                <el-input v-model="scope.row.startWeightFee" @keyup.native="scope.row.startWeightFee = checkInputNum(scope.row.startWeightFee)">编辑区域</el-input>
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" v-if="template.feeType == 2" label="续件(kg)" prop="addWeightStandard">
              <template slot-scope="scope">
                <el-input v-model="scope.row.addWeightStandard" @keyup.native="scope.row.addWeightStandard = checkInputPositiveNum(scope.row.addWeightStandard)">编辑区域</el-input>
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" v-if="template.feeType == 2" label="续费(元)" prop="addWeightFee">
              <template slot-scope="scope">
                <el-input v-model="scope.row.addWeightFee" @keyup.native="scope.row.addWeightFee = checkInputNum(scope.row.addWeightFee)">编辑区域</el-input>
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" v-if="template.feeType == 3" label="首件(立方米)" prop="startVolumeStandard">
              <template slot-scope="scope">
                <el-input v-model="scope.row.startVolumeStandard" @keyup.native="scope.row.startVolumeStandard = checkInputPositiveNum(scope.row.startVolumeStandard)">编辑区域</el-input>
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" v-if="template.feeType == 3" label="运费(元)" prop="startVolumeFee">
              <template slot-scope="scope">
                <el-input v-model="scope.row.startVolumeFee" @keyup.native="scope.row.startVolumeFee = checkInputNum(scope.row.startVolumeFee)">编辑区域</el-input>
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" v-if="template.feeType == 3" label="续件(立方米)" prop="addVolumeStandard">
              <template slot-scope="scope">
                <el-input v-model="scope.row.addVolumeStandard" @keyup.native="scope.row.addVolumeStandard = checkInputPositiveNum(scope.row.addVolumeStandard)">编辑区域</el-input>
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" v-if="template.feeType == 3" label="续费(元)" prop="addVolumeFee">
              <template slot-scope="scope">
                <el-input v-model="scope.row.addVolumeFee" @keyup.native="scope.row.addVolumeFee = checkInputNum(scope.row.addVolumeFee)">编辑区域</el-input>
              </template>
            </el-table-column>
            <el-table-column :key="Math.random()" label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="medium" @click="showUpdateDetail(scope.row)">编辑区域</el-button>
                <el-button type="text" size="medium" @click="deleteTemplateDetail(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <!-- 不配送区域设置 -->
      <el-form label-width="100px">
        <el-form-item label="不配送区域:">
          <el-button type="text" @click="showNotDeliveryArea">编辑不配送区域运费</el-button>
        </el-form-item>
        <el-form-item>
          <el-table :data="notDeliveryAreaNames">
            <el-table-column label="不配送区域" align="center" prop="areaNames"></el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <!-- 保存 返回 -->
      <div class="btn-group-box mar-t-30 mar-b-30" style="text-align:center">
        <el-button type="primary" @click="saveTemplate">保存</el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </div>
    <!-- 添加/编辑配送区域 弹窗 -->
    <el-dialog title="配送区域设置" :visible.sync="deliveryAreaVisable" width="50%">
      <tree-transfer :title="['可选省、市、区', '已选省、市、区']" :from_data='fromDeliveryAreaData' :to_data='toDeliveryAreaData' @addBtn='addDeliveryData' @removeBtn='removeDeliveryData' :defaultProps="treeProps" node_key="areaId" pid="parentId" height='540px' filter>
      </tree-transfer>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deliveryAreaVisable = false">取 消</el-button>
        <el-button type="primary" @click="saveTemplateDetail">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="不配送区域设置" :visible.sync="notDeliveryAreaVisable" width="50%">
      <tree-transfer :title="['可选省、市、区', '已选省、市、区']" :from_data='fromNotDeliveryAreaData' :to_data='toNotDeliveryAreaData' @addBtn='addNotDeliveryData' @removeBtn='removeNotDeliveryData' :defaultProps="treeProps" node_key="areaId" pid="parentId" height='540px' filter>
      </tree-transfer>
      <span slot="footer" class="dialog-footer">
        <el-button @click="notDeliveryAreaVisable = false">取 消</el-button>
        <el-button type="primary" @click="saveNotDeliveryArea">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import treeTransfer from '../components/transfer-extend'
import { getDeliveryTemplate, saveTemplate } from '@/api/sell/delivery-template.js'
import { listArea } from '@/api/area/area'

export default {
  components: { treeTransfer },
  data() {
    return {
      template: {
        templateId: '',
        templateName: '',
        countryFlag: '0',
        templateType: '1',
        feeType: '1',
        startItemStandard: '',
        startItemFee: '',
        addItemStandard: '',
        addItemFee: '',
        startWeightStandard: '',
        startWeightFee: '',
        addWeightStandard: '',
        addWeightFee: '',
        startVolumeStandard: '',
        startVolumeFee: '',
        addVolumeStandard: '',
        addVolumeFee: ''
      },
      notDeliveryAreaNames: [],
      deliveryAreaVisable: false,
      notDeliveryAreaVisable: false,
      treeProps: {
        label: 'areaName',
        children: 'children',
        isLeaf: 'leaf',
        disable: 'disable'
      },
      isAddDetail: false,
      templateDetail: {},
      areaData: [],
      fromDeliveryAreaData: [],
      toDeliveryAreaData: [],
      fromNotDeliveryAreaData: [],
      toNotDeliveryAreaData: [],
      provinceMap: {},
      cityListMap: {},
      cityMap: {},
      districtListMap: {},
      districtMap: {},
      rules: {
        templateName: [
          { required: true, message: '请填写模版名称', trigger: 'blur' }
        ],
        templateType: [
          { required: true, message: '请选择模版类型', trigger: 'blur' }
        ],
        feeType: [
          { required: true, message: '请选择计费方式', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.initAreaList().then(() => {
      const templateId = this.getCurrentPage().query.templateId
      if (templateId) {
        this.template.templateId = templateId
        this.getTemplate()
      }
    })
  },
  methods: {
    initAreaList() {
      return new Promise((resolve, reject) => {
        listArea().then(response => {
          // 将list转为 map(key: parentId, value: areaList)
          response.data.districtList.forEach(area => {
            this.districtMap[area.areaId] = area
            let districtList = this.districtListMap[area.parentId]
            if (!districtList) {
              districtList = []
            }
            districtList.push(area)
            this.districtListMap[area.parentId] = districtList
          })
          response.data.cityList.forEach(area => {
            this.cityMap[area.areaId] = area
            area.children = this.districtListMap[area.areaId]
            let cityList = this.cityListMap[area.parentId]
            if (!cityList) {
              cityList = []
            }
            cityList.push(area)
            this.cityListMap[area.parentId] = cityList
          })
          response.data.provinceList.forEach(area => {
            this.provinceMap[area.areaId] = area
            area.children = this.cityListMap[area.areaId]
          })
          this.areaData = response.data.provinceList
          resolve(true)
        }).catch(err => {
          reject(err)
        })
      })
    },
    getTemplate() {
      const data = {
        templateId: this.template.templateId
      }
      getDeliveryTemplate(data).then((response) => {
        Object.assign(this.template, response.data)
        this.template.countryFlag = response.data.countryFlag.toString()
        this.template.templateType = response.data.templateType.toString()
        this.template.feeType = response.data.feeType.toString()
        this.toNotDeliveryAreaData = []
        this.updateToTree(this.template.notDeliveryAreaList || [], this.toNotDeliveryAreaData)
        const areaNames = this.formatAreaData(this.toNotDeliveryAreaData)
        this.notDeliveryAreaNames = areaNames ? [{ areaNames: areaNames }] : []
      })
    },
    formatAreaList(templateAreaList) {
      const areaData = []
      this.updateToTree(templateAreaList, areaData)
      return this.formatAreaData(areaData)
    },
    formatAreaData(areaData) {
      let areaNames = ''
      areaData.forEach(area => {
        areaNames += area.areaName + ' '
        const cityList = area.children
        if (!cityList) {
          // 香港，台湾，澳门没有城市信息
          return
        }
        let cityNames = ''
        let allDistrict = true
        for (let i = 0; i < cityList.length; i++) {
          const city = cityList[i]
          cityNames += city.areaName + ' '
          const districtList = city.children
          if (!districtList || !this.districtListMap[city.areaId] || districtList.length === this.districtListMap[city.areaId].length) {
            // 包含全部区县，不显示区县
            continue
          } else {
            allDistrict = false
            if (districtList && districtList.length > 0) {
              cityNames += '('
              districtList.forEach(district => { cityNames += district.areaName + ' ' })
              cityNames += ')'
            }
          }
        }
        if (allDistrict && cityList.length === this.cityListMap[area.areaId].length) {
          // 包含全部城市，则不显示城市
          cityNames = ''
        } else {
          cityNames = '[' + cityNames + ']'
        }
        areaNames += cityNames + ' '
      })
      return areaNames
    },
    saveTemplate() {
      if (!this.template.templateDetailsList && this.template.countryFlag === '0') {
        this.$message.error('运费模板中至少要设置默认运费或一个配送区域后才可保存。')
        return
      }
      if (this.template.countryFlag === '1') {
        switch (this.template.feeType) {
          default:
            this.$message.error('请选择计费方式')
            validateResult = false
            return
          case '1':
            if (!this.template.startItemStandard || this.template.startItemStandard * 1 <= 0) {
              this.$message.error('首件件数必须大于0')
              return
            }
            if (!this.template.startItemFee || this.template.startItemFee * 1 < 0) {
              this.$message.error('首件运费必须大于等于0')
              return
            }
            if (this.template.addItemStandard && this.template.addItemStandard * 1 <= 0) {
              this.$message.error('续件件数必须大于0')
              return
            }
            if (this.template.addItemStandard && !this.template.addItemFee) {
              this.$message.error('续费金额不能为空')
              return
            }
            if (this.template.addItemFee && this.template.addItemFee * 1 < 0) {
              this.$message.error('续费金额必须大于等于0')
              return
            }
            break
          case '2':
            if (!this.template.startWeightStandard || this.template.startWeightStandard * 1 <= 0) {
              this.$message.error('首件件数必须大于0')
              return
            }
            if (!this.template.startWeightFee || this.template.startWeightFee * 1 < 0) {
              this.$message.error('首件运费必须大于等于0')
              return
            }
            if (this.template.addWeightStandard && this.template.addWeightStandard * 1 <= 0) {
              this.$message.error('续件件数必须大于0')
              return
            }
            if (this.template.addWeightStandard && !this.template.addWeightFee) {
              this.$message.error('续费金额不能为空')
              return
            }
            if (this.template.addWeightFee && this.template.addWeightFee * 1 < 0) {
              this.$message.error('续费金额必须大于等于0')
              return
            }
            break
          case '3':
            if (!this.template.startVolumeStandard || this.template.startVolumeStandard * 1 <= 0) {
              this.$message.error('首件件数必须大于0')
              return
            }
            if (!this.template.startVolumeFee || this.template.startVolumeFee * 1 < 0) {
              this.$message.error('首件运费必须大于等于0')
              return
            }
            if (this.template.addVolumeStandard && this.template.addVolumeStandard * 1 <= 0) {
              this.$message.error('续件件数必须大于0')
              return
            }
            if (this.template.addVolumeStandard && !this.template.addVolumeFee) {
              this.$message.error('续费金额不能为空')
              return
            }
            if (this.template.addVolumeFee && this.template.addVolumeFee * 1 < 0) {
              this.$message.error('续费金额必须大于等于0')
              return
            }
            break
        }
      }
      let validateResult = true
      this.template.templateDetailsList && this.template.templateDetailsList.forEach(templateDetail => {
        switch (this.template.feeType) {
          default:
            this.$message.error('请选择计费方式')
            validateResult = false
            return
          case '1':
            if (!templateDetail.startItemStandard || templateDetail.startItemStandard * 1 <= 0) {
              this.$message.error('首件件数必须大于0')
              validateResult = false
              return
            }
            if (!templateDetail.startItemFee || templateDetail.startItemFee * 1 < 0) {
              this.$message.error('首件运费必须大于等于0')
              validateResult = false
              return
            }
            if (templateDetail.addItemStandard && templateDetail.addItemStandard * 1 <= 0) {
              this.$message.error('续件件数必须大于0')
              validateResult = false
              return
            }
            if (templateDetail.addItemStandard && !templateDetail.addItemFee) {
              this.$message.error('续费金额不能为空')
              validateResult = false
              return
            }
            if (templateDetail.addItemFee && templateDetail.addItemFee * 1 < 0) {
              this.$message.error('续费金额必须大于等于0')
              validateResult = false
              return
            }
            break
          case '2':
            if (!templateDetail.startWeightStandard || templateDetail.startWeightStandard * 1 <= 0) {
              this.$message.error('首件件数必须大于0')
              validateResult = false
              return
            }
            if (!templateDetail.startWeightFee || templateDetail.startWeightFee * 1 < 0) {
              this.$message.error('首件运费必须大于等于0')
              validateResult = false
              return
            }
            if (templateDetail.addWeightStandard && templateDetail.addWeightStandard * 1 <= 0) {
              this.$message.error('续件件数必须大于0')
              validateResult = false
              return
            }
            if (templateDetail.addWeightStandard && !templateDetail.addWeightFee) {
              this.$message.error('续费金额不能为空')
              validateResult = false
              return
            }
            if (templateDetail.addWeightFee && templateDetail.addWeightFee * 1 < 0) {
              this.$message.error('续费金额必须大于等于0')
              validateResult = false
              return
            }
            break
          case '3':
            if (!templateDetail.startVolumeStandard || templateDetail.startVolumeStandard * 1 <= 0) {
              this.$message.error('首件件数必须大于0')
              validateResult = false
              return
            }
            if (!templateDetail.startVolumeFee || templateDetail.startVolumeFee * 1 < 0) {
              this.$message.error('首件运费必须大于等于0')
              validateResult = false
              return
            }
            if (templateDetail.addVolumeStandard && templateDetail.addVolumeStandard * 1 <= 0) {
              this.$message.error('续件件数必须大于0')
              validateResult = false
              return
            }
            if (templateDetail.addVolumeStandard && !templateDetail.addVolumeFee) {
              this.$message.error('续费金额不能为空')
              validateResult = false
              return
            }
            if (templateDetail.addVolumeFee && templateDetail.addVolumeFee * 1 < 0) {
              this.$message.error('续费金额必须大于等于0')
              validateResult = false
              return
            }
            break
        }
      })
      if (!validateResult) {
        return
      }
      this.template.enterpriseId = this.getEnterpriseId()
      this.template.countryFlag = this.template.countryFlag * 1 === 1 ? '1' : '0'
      saveTemplate(this.template).then(response => {
        if (response.isError) return
        this.$message({ type: 'success', message: '成功!' })
        this.goBack()
      })
    },
    goBack() {
      this.$router.push({ path: '/order/order/express/index', query: { activeName: 'deliveryTemplate' }})
    },
    // 监听穿梭框组件添加
    addDeliveryData(fromData, toData, obj) {
      console.log(toData)
      // 树形穿梭框模式transfer时，返回参数为左侧树移动后数据、右侧树移动后数据、移动的{keys,nodes,halfKeys,halfNodes}对象
      this.toDeliveryAreaData = toData
    },
    // 监听穿梭框组件移除
    removeDeliveryData(fromData, toData, obj) {
      // 树形穿梭框模式transfer时，返回参数为左侧树移动后数据、右侧树移动后数据、移动的{keys,nodes,halfKeys,halfNodes}对象
      this.toDeliveryAreaData = toData
    },
    addNotDeliveryData(fromData, toData, obj) {
      this.toNotDeliveryAreaData = toData
    },
    removeNotDeliveryData(fromData, toData, obj) {
      this.toNotDeliveryAreaData = toData
    },
    showAddDetail() {
      this.isAddDetail = true
      this.fromDeliveryAreaData = JSON.parse(JSON.stringify(this.areaData))
      this.fromDeliveryAreaData = this.filterArea(this.fromDeliveryAreaData, this.template.templateDetailsList)
      this.toDeliveryAreaData = []
      this.templateDetail = {
        templateId: this.template.templateId,
        containsFlag: 1,
        startItemStandard: 1,
        startWeightStandard: 1,
        startVolumeStandard: 1,
        startItemFee: '',
        startWeightFee: '',
        startVolumeFee: '',
        addItemStandard: 1,
        addWeightStandard: 1,
        addVolumeStandard: 1,
        addItemFee: '',
        addWeightFee: '',
        addVolumeFee: ''
      }
      this.deliveryAreaVisable = true
    },
    filterArea(fromDeliveryAreaData, templateDetailsList) {
      let selectedAreaList = []
      templateDetailsList && templateDetailsList.forEach((details) => { selectedAreaList = selectedAreaList.concat(details.templateAreaList || []) })
      const selectedAreaIds = this.getSelectedAreaIds(selectedAreaList)
      fromDeliveryAreaData = fromDeliveryAreaData.filter(province => {
        if (selectedAreaIds.includes(province.areaId)) {
          // 整个省份过滤
          return false
        }
        if (province.children && province.children.length > 0) {
          province.children = province.children.filter(city => {
            if (selectedAreaIds.includes(province.areaId)) {
              // 整个城市过滤
              return false
            }
            if (city.children && city.children.length > 0) {
              city.children = city.children.filter(district => !selectedAreaIds.includes(district.areaId))
            }
            return true
          })
        }
        return true
      })
      return fromDeliveryAreaData
    },
    // 获取区域树中已勾选的区域id，如果下级区域都已勾选，只显示上级id，反之只显示下级id
    getSelectedAreaIds(areaList) {
      const selectAreas = []
      this.updateToTree(areaList, selectAreas)

      const selectedAreaIds = []
      selectAreas.forEach(province => {
        const cityList = this.provinceMap[province.areaId].children
        const allCity = cityList && province.children && cityList.length === province.children.length
        let allDistrict = true
        const cityIds = []
        province.children && province.children.forEach(city => {
          const districtList = this.cityMap[city.areaId].children
          // 城市下的所有区县是否都选中
          const cityAllDistrict = districtList && city.children && districtList.length === city.children.length
          if (cityAllDistrict) {
            // 如果包含所有区县，只记录城市id
            cityIds.push(city.areaId)
          } else {
            // 不是全部城市的全部区县都选中，不记录省份id
            allDistrict = false
            // 只包含部分区县，则记录区县id，不记录城市id
            if (city.children && city.children.length > 0) {
              city.children.forEach(district => selectedAreaIds.push(district.areaId))
            }
          }
        })
        if (allCity && allDistrict) {
          // 全部城市的全部区县都选中，只记录省份id
          selectedAreaIds.push(province.areaId)
        } else {
          cityIds.forEach(cityId => selectedAreaIds.push(cityId))
        }
      })
      return selectedAreaIds
    },
    showUpdateDetail(row) {
      this.isAddDetail = false
      this.fromDeliveryAreaData = JSON.parse(JSON.stringify(this.areaData))
      this.fromDeliveryAreaData = this.filterArea(this.fromDeliveryAreaData, this.template.templateDetailsList)
      this.templateDetail = row
      this.toDeliveryAreaData = []
      this.updateToTree(this.templateDetail.templateAreaList || [], this.toDeliveryAreaData)
      this.deliveryAreaVisable = true
    },
    showNotDeliveryArea() {
      this.fromNotDeliveryAreaData = JSON.parse(JSON.stringify(this.areaData))
      this.toNotDeliveryAreaData = []
      this.updateToTree(this.template.notDeliveryAreaList || [], this.toNotDeliveryAreaData)
      this.notDeliveryAreaVisable = true
    },
    // 将省市区从列表转为树
    updateToTree(areaList, toData) {
      const areaIds = areaList.map(a => a.areaId)
      const areaData = {}
      // 根据区域id构建完整的省市区树
      areaIds.forEach(areaId => {
        const district = this.districtMap[areaId]
        let cityId
        if (district) {
          if (!areaData[areaId]) {
            areaData[areaId] = Object.assign({}, district)
            areaData[areaId].children = []
          }
          cityId = district.parentId
        } else {
          cityId = areaId
        }
        const city = this.cityMap[cityId]
        let provinceId
        if (city) {
          if (!areaData[cityId]) {
            areaData[cityId] = Object.assign({}, city)
            areaData[cityId].children = []
          }
          provinceId = city.parentId
        } else {
          provinceId = areaId
        }
        const province = this.provinceMap[provinceId]
        if (province) {
          if (!areaData[provinceId]) {
            areaData[provinceId] = Object.assign({}, province)
            areaData[provinceId].children = []
          }
        }
      })
      const areaMap = {}
      areaIds.forEach(areaId => {
        let area = areaData[areaId]
        if (!area) {
          return
        }
        const isProvince = !area.parentId || area.parentId === '0'
        if (isProvince) {
          if (!areaMap[area.areaId]) {
            // 添加省份
            areaMap[area.areaId] = area
            toData.push(area)
          }
          return
        }
        while (area.parentId && area.parentId !== '0') {
          const parent = areaData[area.parentId]
          if (!parent) {
            console.log('根据父id找不到区域信息：' + area.parentId)
            return
          }
          let children = parent.children
          if (!children) {
            children = []
          }
          // id相同的数据不重复加入children
          if (children.filter(a => a.areaId === area.areaId).length === 0) {
            children.push(area)
          }
          parent.children = children
          area = parent
          if (!area.parentId && !areaMap[area.areaId]) {
            areaMap[area.areaId] = area
            toData.push(area)
          }
        }
      })
    },
    deleteTemplateDetail(index) {
      this.template.templateDetailsList.splice(index, 1)
    },
    // 保存不配送区域设置到内存
    saveNotDeliveryArea() {
      this.template.notDeliveryAreaList = []
      this.toNotDeliveryAreaData.forEach(area => {
        this.addTemplateArea(area, this.template.notDeliveryAreaList, '', 0)
      })
      const areaNames = this.formatAreaData(this.toNotDeliveryAreaData)
      this.notDeliveryAreaNames = areaNames ? [{ areaNames: areaNames }] : []
      this.notDeliveryAreaVisable = false
    },
    // 保存区域设置到内存
    saveTemplateDetail() {
      this.templateDetail.templateAreaList = []
      this.toDeliveryAreaData.forEach(area => {
        this.addTemplateArea(area, this.templateDetail.templateAreaList, this.templateDetail.templateDetailsId, 1)
      })
      if (this.isAddDetail) {
        if (!this.template.templateDetailsList) {
          this.template.templateDetailsList = []
        }
        this.template.templateDetailsList.push(this.templateDetail)
      }
      this.deliveryAreaVisable = false
    },
    // 递归添加省市区
    addTemplateArea(area, areaList, templateDetailsId, containsFlag) {
      areaList.push({
        areaId: area.areaId,
        templateId: this.template.templateId,
        containsFlag: containsFlag,
        templateDetailsId: templateDetailsId
      })
      if (area.children && area.children.length > 0) {
        area.children.forEach(child => this.addTemplateArea(child, areaList, templateDetailsId, containsFlag))
      }
    }
  }
}
</script>

<style scoped lang='less'>
  .bill-box {
    /deep/ .el-form-item__content {
      margin-left: 0px !important;
    }
    /deep/ .el-form-item--medium {
      width: 200px;
      display: inline-block
    }
  }
  /deep/ .el-dialog__body {
    padding: 20px;
  }
</style>